package net.e4net.watrix.example.base.factory;

import java.sql.Connection;
import java.util.Hashtable;
import java.util.Properties;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

import net.e4net.watrix.common.CommonException;
import net.e4net.watrix.common.dao.DbConnection;
import net.e4net.watrix.common.dao.DbConnectionFactory;
import net.e4net.watrix.example.common.ExamProperties;

public class ExamDbConnectionFactory extends DbConnectionFactory {
    protected static DataSource dataSource = null;
    protected static Object lock = new Object();

    public Connection getConnection(Properties prop) throws CommonException {

        Connection con = null;

        ExamProperties examProp = ExamProperties.getInstance();
        String poolname = examProp.getProperty("JNDI_DBPOOL_NAME");
        String factory  = examProp.getProperty("INITIAL_CONTEXT_FACTORY");

        try {
            if ( dataSource == null ) {
                Context ctx = null;
                if ( factory.length() > 0 ) {
                    Hashtable ht = new Hashtable();
                    ht.put(Context.INITIAL_CONTEXT_FACTORY, factory);
                    ctx = new InitialContext(ht);
                } else {
                    ctx = new InitialContext();
                }
                DataSource ds = (DataSource) ctx.lookup( poolname );
                synchronized (lock) {
                    dataSource = ds;
                }
            }

            con = DbConnection.getInstance( dataSource.getConnection(), this.getClass().getName() );

        } catch( Throwable t) {
            throw new CommonException( ExamProperties.getMessage("dbConnectionFailed") ,t);
        }

        if ( con == null ) throw new CommonException( ExamProperties.getMessage("dbConnectionFailed") );

        return con;
    }
}
